package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

var (
	HOST  = "127.0.0.1"
	PORT  = "3333"
	PROTO = "tcp"
)

func main() {
	l, err := net.Listen(PROTO, HOST+":"+PORT)
	if err != nil {
		fmt.Println("监听失败：", err)
		return
	}
	defer l.Close()

	for {
		conn, err := l.Accept()
		if err != nil {
			fmt.Println("Error accepting ... ", err)
			os.Exit(1)
		}
		go handleRequest(conn)
	}
}

func handleRequest(conn net.Conn) {
	buf, readErr := io.ReadAll(conn)
	if readErr != nil {
		fmt.Println("read failed : ", readErr)
		os.Exit(1)
	}
	fmt.Println("got : ", string(buf))

	_, writeErr := conn.Write([]byte("message recieved.\n"))
	if writeErr != nil {
		fmt.Println("write error : ", writeErr)
		os.Exit(1)
	}
	conn.Close()
}
